<template>
  <div class="article-page">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>面经后台</el-breadcrumb-item>
      <el-breadcrumb-item>面经管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" border="false">
      <template #header>
        <div class="header">
          <!-- 头部内容 -->
          <span>共 343 条记录</span>
          <el-button
            @click="showDrawer('add')"
            type="primary"
            round
            size="small"
            icon="el-icon-plus"
            >添加面经</el-button
          >
        </div>
      </template>
      <!-- 表格 -->
      <el-table :data="tableData" style="width: 100%">
        <!-- el-table-column代表列 -->
        <el-table-column prop="stem" label="标题" ></el-table-column>

        <el-table-column prop="creator" label="作者" width="130">
        </el-table-column>

        <el-table-column prop="likeCount" label="点赞" width="80">
        </el-table-column>
        <el-table-column prop="views" label="浏览数" width="80">
        </el-table-column>
        <el-table-column prop="createdAt" label="更新时间" width="180">
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <!-- scope有当前这一行的相关信息 -->
            <!-- 其中scope.row就是这一行的数据 -->
            <!-- 预览 -->
            <el-link @click="showDrawer('view', scope.row.id)"
              ><i style="font-size: 18px" class="el-icon-view"></i
            ></el-link>
            <!-- 编辑 -->
            <el-link @click="showDrawer('edit', scope.row.id)"
              ><i
                style="font-size: 18px;margin:0 10px;"
                class="el-icon-edit-outline"
              ></i
            ></el-link>
            <!-- 删除 -->
            <el-link @click="del(scope.row.id)"
              ><i style="font-size: 18px" class="el-icon-delete"></i
            ></el-link>
          </template>
        </el-table-column>
      </el-table>

      <!--
        layout就是指设置分页的布局
          prev代表上一页 pager代表页码 next代表下一页
        total：设置数据总数
       -->
      <el-pagination
        @current-change="changePage"
        :current-page="page"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 抽屉效果组件 -->
    <!-- 如果对着标签属性不加冒号，给的值永远都是字符串 -->
    <el-drawer
      :title="title"
      :visible.sync="drawer"
      direction="rtl"
      :size="600"
      :before-close="beforeClose"
    >
      <div v-if="type === 'view'" class="article-preview">
        <h5>{{ form.stem }}</h5>
        <div v-html="form.content"></div>
      </div>
      <el-form
        v-else
        :model="form"
        :rules="rules"
        ref="form"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="标题" prop="stem">
          <el-input v-model="form.stem"></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <!-- 校验规则是给表单元素用的，但此时富文本不是表单元素 -->
          <!-- 所以就校验不了了 -->
          <!-- 所以该自己手动写代码来校验它 -->
          <quill-editor
            v-model="form.content"
            @blur="$refs.form.validateField('content')"
          ></quill-editor>
        </el-form-item>
        <el-form-item>
          <el-button @click="save" type="primary">确认</el-button>
          <el-button @click="beforeClose">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script>
// 导入接口
import { articleListAPI, addArticleAPI, delArticleAPI, detailAPI, updateAPI } from '@/api/article'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'

import { quillEditor } from 'vue-quill-editor'

export default {
  name: 'article-page',
  components: {
    quillEditor
  },
  data () {
    return {
      // 控制抽屉的显示和隐藏
      drawer: false,
      // 只能绑定数组
      tableData: [],
      pageSize: 5,
      total: 0,
      page: 1,
      // 用来保存被点的抽屉的类型
      type: 'add',
      form: {
        stem: '',
        content: ''
      },
      rules: {
        stem: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  created () {
    this.loadData()
  },
  methods: {
    async del (id) {
      // 发请求做删除
      await delArticleAPI({
        id
      })
      // 弹出提示
      this.$message.success('删除成功')
      // 如果只剩最后一条
      if (this.tableData.length === 1 && this.page !== 1) {
        this.page--
      }
      // 重新渲染数据
      this.loadData()
    },
    // 关闭前触发，必须调用形参done才能关闭，不调用就不关闭了
    beforeClose () {
      // 把内容清空
      this.form = {
        stem: '',
        content: ''
      }
      // this.$refs.form.resetFields()
      // 清空指定的校验结果
      if (this.type !== 'view') {
        this.$refs.form.clearValidate(['stem', 'content'])
      }
      this.drawer = false
    },
    // 点击确定触发的事件
    async save () {
      try {
        // 整个表单校验
        await this.$refs.form.validate()
        if (this.type === 'add') {
        // 能来到这，证明校验通过，就要发请求做新增
          await addArticleAPI(this.form)
          // 弹出成功提示
          this.$message.success('新增成功')
          // 渲染数据
          this.page = 1
        } else {
          // 修改
          await updateAPI({
            id: this.form.id,
            content: this.form.content,
            stem: this.form.stem
          })
          this.$message.success('修改成功')
        }
        // 关闭抽屉 - 它仅仅只是把变量改为false直接隐藏
        // 并不会触发关闭前的钩子
        // this.drawer = false
        this.beforeClose()
        this.loadData()
      } catch {}
    },
    // 发请求加载数据的方法
    async loadData () {
      const res = await articleListAPI({
        current: this.page,
        pageSize: this.pageSize
      })
      // 总页数给分页保存
      this.total = res.data.total
      // 把数据给table
      this.tableData = res.data.rows
    },
    // 页码改变事件
    changePage (page) {
      // 为了发请求，应该用最新的页码发请求
      this.page = page
      this.loadData()
    },

    // 点击新增、查看、编辑触发的事件
    async showDrawer (type, id) {
      // 把被点的类型保存起来
      this.type = type

      // 先发请求，再显示
      if (type !== 'add') {
        const res = await detailAPI({
          id
        })
        // 把请求到的数据给表单双向绑定的form，form一变界面就变了
        this.form = res.data
      }

      // 显示出抽屉
      this.drawer = true
    }
  },
  computed: {
    title () {
      if (this.type === 'add') {
        return '添加面经'
      } else if (this.type === 'edit') {
        return '修改面经'
      } else {
        return '预览面经'
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 25px;
  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-right: 16px;
  }
  .actions {
    font-size: 18px;
    display: flex;
    justify-content: space-around;
    color: #666;
    > i:hover {
      color: rgba(114, 124, 245, 1);
      cursor: pointer;
    }
  }
}
.el-pagination {
  margin-top: 20px;
  text-align: center;
}
.el-breadcrumb {
  margin-top: 10px;
}
.el-form {
  padding-right: 40px;
}
.quill-editor {
  ::v-deep .ql-editor {
    height: 300px;
  }
}
.el-rate {
  padding: 10px 0;
}
.article-preview {
  padding: 0 40px 40px 40px;
  > h5 {
    font-size: 20px;
    color: #666;
    border-bottom: 1px dashed #ccc;
    padding-bottom: 30px;
    margin: 0 0 20px 0;
  }
}
</style>
